<?php


namespace core\utils;


use ArrayAccess;

class Form implements ArrayAccess
{
    public $params = [];
    const PAGE_NO_FIELD = 'page';
    const PAGE_SIZE_FIELD = 'pageSize';

    public function __construct($params = [])
    {
        $this->params = array_merge($this->params, $params);
    }

    static function getForm($params)
    {
        return new Form($params);
    }


    /**
     * 页数
     * @return int
     */
    public function getPage()
    {
        return intval($this->params[self::PAGE_NO_FIELD] ?? 1);
    }

    /**
     * 偏移量
     * @return int
     */
    public function getOffset()
    {
        return (intval($this->params[self::PAGE_NO_FIELD] ?? 1) - 1) * $this->getPageSize();
    }

    /**
     * @return int
     */
    public function getPageSize()
    {
        return intval($this->params[self::PAGE_SIZE_FIELD] ?? 10);
    }

    public function offsetExists($offset)
    {
        return isset($this->params[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->params[$offset] ?? null;
    }

    public function offsetSet($offset, $value)
    {
        $this->params[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->params[$offset]);
    }

    /**
     * @param string $default
     * @return string
     */
    public function getSortField($default = "")
    {
        return $this->params['prop'] ?? $default;
    }

    /**
     * @param string $default
     * @return string
     */
    public function getOrder($default = "")
    {
        $qOrder = $this->params['order'] ?? "";
        $order = "";
        if ($qOrder == 'ascending') {
            $order = 'asc';
        }
        if ($qOrder == 'descending') {
            $order = 'desc';
        }
        return $order ?: $default;
    }

    public function needOrder()
    {
        return  $this->getSortField() && $this->getOrder();
    }

}